﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gueei.Gallery.Core.Services;
using Gueei.Gallery.Core.ViewModels;
using Gueei.Gallery.Web.Exceptions;

namespace Gueei.Gallery.Web.Controllers
{
    public class BatchUploadController : Controller
    {
    	private readonly BatchImportService _batchImportService;
		public BatchUploadController(BatchImportService batchImportService)
		{
			_batchImportService = batchImportService;
		}

        public ActionResult Index()
        {
        	return View(_batchImportService.StartNewBatch());
        }

		[HttpPost]
		public ActionResult AsyncUpload(HttpPostedFileBase qqfile, Guid batchId)
		{
			// Handler for non IE
			if (qqfile == null)
			{
				var fileName = Request["qqfile"];
				// then the file is from the raw stream
				_batchImportService.AddToBatch(batchId, Request.InputStream, fileName);
			}
			else
			{
				_batchImportService.AddToBatch(batchId, qqfile.InputStream, qqfile.FileName);
			}
			return new ContentResult {Content = "{success:true}"};
		}

		[HttpPost]
		public ActionResult Index(BatchFileImportViewModel model)
		{
			if (ModelState.IsValid)
			{
				model.Images = _batchImportService.GetTempImages(model.BatchId);
				return View("PendingBatch", model);
			}
			else
			{
				return View(model);
			}
		}
	}
}
